using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using System.Text.RegularExpressions;
using WpfRegexDesigner.Controller;

namespace WpfRegexDesigner
{
	/// <summary>
	/// Interaction logic for Window1.xaml
	/// </summary>
	public partial class MainWindow : Window
	{
		public MainWindow()
		{

			InitializeComponent();

			// Set up the commands for the application. I think there's a cooler way, through xaml - need to investigate further.
			CommandBinding executeRegexCommandBinding = new CommandBinding(RegexDesignerCommands.ExecuteRegexCommand);
			executeRegexCommandBinding.Executed += new ExecutedRoutedEventHandler(cbd_Executed);
			CommandBindings.Add(executeRegexCommandBinding);

			CommandBinding toolsOptionsCommandBinding = new CommandBinding(RegexDesignerCommands.ToolsOptionsCommand);
			toolsOptionsCommandBinding.Executed += new ExecutedRoutedEventHandler(toolsOptionsCommandBinding_Executed);
			CommandBindings.Add(toolsOptionsCommandBinding);

			DataContext = regexData;

			//regexTextBox.Text = "(?<protocol>http|ftp)://(?<domain>[^/\\r\\n]+)(?<path>/[^\\r\\n]*)?";
			//replaceExpressionTextBox.Text = Properties.Resources.DefaultReplacementExpression;
		}

		Model.RegexData regexData = new Model.RegexData
		{
			RegularExpression = "((?<word>[a-z]+\\w*?)|(?<capitalizedword>[A-Z]+\\w*?))(?<nonword>[^\\w]+)",
			InputText = "This is a sentence about London; however, THIS is something else entirely.",
			ReplacementExpression = "Word: ${word}${capitalizedword}" + Environment.NewLine
		};


		void toolsOptionsCommandBinding_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			MessageBox.Show("Tools / Options - coming soon!");
		}

		void cbd_Executed(object sender, ExecutedRoutedEventArgs e)
		{
			ExecuteRegex();
		}

		/// <summary>
		/// Executes the regular expression and sets up the UI accordingly.
		/// </summary>
		void ExecuteRegex()
		{
			try
			{
				resultsTreeView.Focus(); 
				regexData.Execute();
			}
			catch (Exception ex)
			{
				MessageBox.Show(
					string.Format(
					"There was a problem executing the expression:{0}{0}{1}", Environment.NewLine, ex.ToString()),
					"Error",
					MessageBoxButton.OK, MessageBoxImage.Error);

				return;
			}
			inputTextTabControl.SelectedItem = inputTextResultsTab;
			ExpandFirstLevelTreeNodes(resultsTreeView);
		}

		/// <summary>
		/// When a new object is selected in the Results tree view, highlights the corresponding (matched)
		/// text in the inputRichTextBox control.
		/// </summary>
		/// <param name="sender"></param>
		/// <param name="args"></param>
		protected void resultsTreeView_SelectedItemChanged(object sender, RoutedEventArgs args)
		{
			if (resultsTreeView.SelectedItem == null)
			{
				return;
			}
			Model.IRegexInfo rinfo = resultsTreeView.SelectedItem as Model.IRegexInfo;
			System.Diagnostics.Debug.Assert(rinfo != null, "resultsTreeView_SelectedItemChanged could not coerce the tree view's selected item into an IRegexInfo");

			inputTextTabControl.SelectedItem = inputTextResultsTab;
			regexData.SetMatchedTextProperties(rinfo.Index, rinfo.Length);
		
		}

		private void ExpandFirstLevelTreeNodes(TreeView tree)
		{
			foreach (object item in tree.Items)
			{
				TreeViewItem treeItem = tree.ItemContainerGenerator.ContainerFromItem(item) as TreeViewItem;
				//if (treeItem != null)
				//   ExpandAll(treeItem, true);
				treeItem.IsExpanded = true;
			}
		}

		//private void ExpandAll(ItemsControl items, bool expand)
		//{
		//   foreach (object obj in items.Items)
		//   {
		//      ItemsControl childControl = items.ItemContainerGenerator.ContainerFromItem(obj) as ItemsControl;
		//      if (childControl != null)
		//      {
		//         ExpandAll(childControl, expand);
		//      }
		//      TreeViewItem item = childControl as TreeViewItem;
		//      if (item != null)
		//         item.IsExpanded = true;
		//   }
		//}

		private void itemsList_PreviewKeyDown(object sender, KeyEventArgs e)
		{
			if (e.Key == Key.Space)
			{
				e.Handled = true;
				ListBox lbox = sender as ListBox;
				if (lbox == null)
				{
					MessageBox.Show(sender.GetType().FullName);
					return;
				}
				Model.RegexOptionsValue rov = lbox.SelectedItem as Model.RegexOptionsValue;
				if (rov == null)
				{
					MessageBox.Show(lbox.SelectedItem.GetType().FullName);
					return;
				}
				rov.IsSelected = !rov.IsSelected;
			}
		}
	}
}
